package com.lst.servlet;

import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.entity.request.ClientReqPara;
import com.lst.entity.response.ClientResPara;
import com.lst.model.MstClient;
import com.lst.service.MstClientService;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;

/**
 * @ClassName: RegisterServlet
 * @Description: 注册接口
 * @author zhanghl
 * @date 2016年9月26日 上午10:03:57
 * 
 */
public class RegisterServlet extends BaseServlet {

	private static final long serialVersionUID = 1L;

	private MstClientService mstClientService = ctx.getBean(MstClientService.class);

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();
		logger.info("doPost begin: " + startDate);

		ClientResPara resPara = new ClientResPara();

		try {
			ClientReqPara reqPara = getReqPara(request);

			if (isCheckField(reqPara, resPara)) {
				String mobileno = reqPara.getMobileno();
				String password = reqPara.getPassword();
				
				if(isChinaPhoneLegal(mobileno)){
					MstClient mstclient = new MstClient();
					mstclient.setMobileno(mobileno);
					mstclient.setPassword(password);
					mstclient.setCreatedate(startDate);
					mstclient.setGender(true);
					mstclient.setEnabled(true);
					mstclient.setIsdeleted(false);
					mstclient.setThirdno(null);
					mstclient.setNickname("功夫小白");
					mstclient.setLogintype(CommCode.SYSTEM_LOGINTYPE_MOBILENO);

					Map<String, Object> reqMap = new HashMap<String, Object>();

					reqMap.put("mobileno", mobileno);
					reqMap.put("enabled", true);
					reqMap.put("isDeleted", false);

					List<MstClient> list = mstClientService.queryByList(reqMap,new PageBounds());
					if (list.size() == 0) {

						mstClientService.insert(mstclient);

						String mobile = mstclient.getMobileno().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
						mstclient.setMobile(mobile);

						resPara.setCode(CommCode.M_Y000000);
						resPara.setMessage(CommCode.M_Y000001);
						resPara.setMstClient(mstclient);
					} else {
						resPara.setCode(CommCode.M_A000000);
						resPara.setMessage(CommCode.M_C000006);
					}
				}else{
					resPara.setCode(CommCode.M_A000000);
					resPara.setMessage("手机格式不正确");
				}

				
			}

		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}

		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
					.excludeFieldsWithoutExposeAnnotation().serializeNulls()
					.create();
			String jsonResult = gson.toJson(resPara);

			logger.info("RegisterServlet jsonResult: " + jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

			logger.info("doPost end: " + DateUtil.calLastedTime(startDate));

		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public ClientReqPara getReqPara(HttpServletRequest request) {

		ClientReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request,
					new ClientReqPara());

			reqPara = (ClientReqPara) baseRequest.clone();

			String mobileno = request.getParameter("mobileno");
			String password = request.getParameter("password");

			logger.info("reqPara mobileno: " + mobileno);
			logger.info("reqPara password: " + password);

			reqPara.setMobileno(mobileno);
			reqPara.setPassword(password);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		ClientReqPara registerReqPara = (ClientReqPara) reqPara;
		ClientResPara registerResPara = (ClientResPara) resPara;
		
		if (StringUtils.isEmpty(registerReqPara.getMobileno())) {
			registerResPara.setCode(CommCode.M_A000000);
			registerResPara.setMessage(CommCode.M_P000004);
		} else if (StringUtils.isEmpty(registerReqPara.getPassword())) {
			registerResPara.setCode(CommCode.M_A000000);
			registerResPara.setMessage(CommCode.M_C000002);
		}else {
			flag = true;
		}

		return flag;
	}
	
    /** 
     * 大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数 
     */  
    public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {  
        String regExp = "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";  
        Pattern p = Pattern.compile(regExp);  
        Matcher m = p.matcher(str);  
        return m.matches();  
    } 
    
}
